package com.example.contentresolvertest

import android.annotation.SuppressLint
import android.content.ContentValues
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.core.content.contentValuesOf
import kotlinx.android.synthetic.main.activity_provider_test.*

class ProviderTestActivity : AppCompatActivity() {

    var bookId:String?=null
    private val authority = "com.example.filepersistencetest.provider"

    @SuppressLint("Range")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_provider_test)

        btnAdd.setOnClickListener {
            val uri = Uri.parse("content://$authority/book")
            val values = contentValuesOf("name" to "A clash of kings",
            "author" to "George Martin","pages" to 1040,"price" to 22.85)
            val newUri = contentResolver.insert(uri,values)
            bookId = newUri?.pathSegments?.get(1)
        }

        btnQuery.setOnClickListener {
            val uri = Uri.parse("content://$authority/book")
            contentResolver.query(uri,null,null,null,null)?.apply {
                while (moveToNext()){
                    val name = getString(getColumnIndex("name"))
                    val author = getString(getColumnIndex("author"))
                    val pages = getString(getColumnIndex("pages"))
                    val price = getString(getColumnIndex("price"))

                    Log.d("MyActivity", "book name is $name")
                    Log.d("MyActivity", "book author is $author")
                    Log.d("MyActivity", "book pages is $pages")
                    Log.d("MyActivity", "book price is $price")
                }
                close()
            }
        }

        btnDelete.setOnClickListener {
            bookId?.let {
                val uri = Uri.parse("content://$authority/book/$it")
                contentResolver.delete(uri,null,null)
            }
        }
        btnUpdate.setOnClickListener {
            bookId?.let{
                val uri = Uri.parse("content://$authority/book/$it")
                val values = contentValuesOf("name" to "A storm of Swords","pages" to 1216,"price" to 24.05)
                contentResolver.update(uri,values,null,null)
            }
        }
    }
}